<?php

namespace app\admin\service;

use app\model\Link;
use app\model\PayRecord;
use app\model\Videos;
use app\model\VideoDetails;
use app\model\OfficialAccounts;
use app\model\User;
use app\model\DailyDeliveryData;
use app\common\Common;
use think\facade\Cache;
use app\model\Applet;
use app\model\ResponsibilityPerson;
use function Sodium\add;

class AllianceService
{
    private $linkModel;
    private $payRecordModel;
    private $videoModel;
    private $videoDetailModel;
    private $officialAccountsModel;
    private $userModel;
    private $dailyDeliveryDataModel;
    private $appletModel;
    private $responsibilityPersonModel;

    public function __construct(Link $linkModel, PayRecord $payRecordModel, Videos $videoModel, VideoDetails $videoDetailModel, OfficialAccounts $officialAccountsModel, User $userModel, DailyDeliveryData $dailyDeliveryDataModel, Applet $appletModel, ResponsibilityPerson $responsibilityPersonModel)
    {
        $this->linkModel = $linkModel;
        $this->payRecordModel = $payRecordModel;
        $this->videoModel = $videoModel;
        $this->videoDetailModel = $videoDetailModel;
        $this->officialAccountsModel = $officialAccountsModel;
        $this->userModel = $userModel;
        $this->dailyDeliveryDataModel = $dailyDeliveryDataModel;
        $this->appletModel = $appletModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
    }

    // 获取推广链接列表
    public function getPromotionLinkList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $where = [];
        if (!empty($params['id'])) {
            $where[] = ['id' ,'=',$params['id']];
        }
        if (!empty($params['distributor_id'])) {
            $ids     =   $this->responsibilityPersonModel->where('pid',$params['distributor_id'])->column('id');
            $where[] = ['responsibility_person_id' ,'in', $ids];
        }
        if (!empty($params['official_account_id'])) {
            $accounts_data = $this->officialAccountsModel->getInfoByWhere(['applet_id' => $params['official_account_id']], 'id');
            $where[] = ['official_account_id' , '=' , $accounts_data['id']];
        }
        if (!empty($params['start_date'])) {
            $startDate = strtotime($params['start_date']);
            $where[] = ['created_at', '>', $startDate];
        }
        if (!empty($params['end_date'])) {
            $endDate = strtotime($params['end_date'] . ' 23:59:59');
            $where[] = ['created_at', '<', $endDate];
        }

        $data = $this->linkModel->getPagingDataByWhere($where, $page, $limit, 'id, url, media_id, official_account_id, video_id, video_detail_id, is_open, echo_rule_config_id, recharge_template_id, created_at, recharge_price, spend, advertiser_id, version, project_id, echo_rate, link_switch, responsibility_person_id, subject_id');

        if ($data['data']) {
            $videoIds = $linkIds = $officialAccountIds = $responsibilityPersonIds = [];
            foreach ($data['data'] as $value) {
                $videoIds[] = $value['video_id'];
                $linkIds[] = $value['id'];
                $officialAccountIds[] = $value['official_account_id'];
                $responsibilityPersonIds[] = $value['responsibility_person_id'];
            }

            // 获取短剧
            $videoData = $this->videoModel->getDataByIds($videoIds, 'id, name');
            $video = array_column($videoData, 'name', 'id');

            // 获取小程序
            $officialAccountData = $this->officialAccountsModel->getDataByWhere(['id' => $officialAccountIds], 'id, applet_id');
            $appletIds = array_column($officialAccountData, 'applet_id');
            $officialAccount = array_column($officialAccountData, 'applet_id', 'id');
            $appletData = $this->appletModel->getDataByWhere(['id' => $appletIds], 'id, name');
            $applet = array_column($appletData, 'name', 'id');
            $officialAccountResult = [];
            foreach ($officialAccount as $key => $value) {
                $officialAccountResult[$key] = $applet[$value];
            }

            // 获取历史花费
            $deliveryData = $this->dailyDeliveryDataModel->getDataByWhere(['link_id' => $linkIds], 'link_id, cost');
            $costData = [];
            foreach ($deliveryData as $key => $value) {
                $costData[$value['link_id']][] = $value['cost'];
            }

            // 获取负责人
            $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
            $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

            foreach ($data['data'] as $key => $item) {
                // 获取新版巨量今日实时花费
                $totalSpend = empty($costData[$item['id']]) ? 0 : array_sum($costData[$item['id']]);
                $todayCost = 0;
                if ($item['media_id'] == 1) {
                    // 抖音
                    $todayCost = self::getTiktokCost($item);
                } else if ($item['media_id'] == 2) {
                    // 快手
                    $todayCost = self::getKwaiCost($item);
                } else if ($item['media_id'] == 3) {
                    // 百度
                    $todayCost = self::getBaiduCost($item);
                }

                $DayActivaterecharge    =   $this->payRecordModel->where(['activation_date'=>date('Ymd'),'status'=>1,'link_id'=>$item['id']])
                    ->whereTime('pay_time','today')->sum('total_fee');//今日激活充值
                $countNumUid            =   $this->payRecordModel->getPeopleNumber(['link_id'=>$item['id'],'status'=>1],'uid');//查询此推广链接充值总人数

                $data['data'][$key]['spend'] = round($totalSpend,2);
                $data['data'][$key]['today_cost']   = round($todayCost, 2); // 今日花费
                $data['data'][$key]['day_recharge'] = $DayActivaterecharge;//今日激活充值
                if($countNumUid>0 && $item['recharge_price']>0)
                {
                    $data['data'][$key]['percapita_recharge']   = round($item['recharge_price']/$countNumUid,2);//人均花费
                }else{
                    $data['data'][$key]['percapita_recharge']   = 0;//人均花费
                }
                $data['data'][$key]['revenue'] = round($item['recharge_price'] - $totalSpend, 2);
                $data['data'][$key]['video_name'] = empty($video[$item['video_id']]) ? '' : $video[$item['video_id']];
                $data['data'][$key]['applet_name'] = empty($officialAccountResult[$item['official_account_id']]) ? '' : $officialAccountResult[$item['official_account_id']];
                $data['data'][$key]['responsibility_person'] = empty($responsibilityPerson[$item['responsibility_person_id']]) ? '' : $responsibilityPerson[$item['responsibility_person_id']];
            }
        }

        return $data;
    }

    // 获取抖音花费
    public function getTiktokCost($params)
    {
        $realTimeSpend = 0;
        // 获取accessToken
        $redis = Cache::store('redis')->handler();
        $redis->select(5);

        $appId = config('tiktok.huge_amount.app_id');
        $secret = config('tiktok.huge_amount.secret');
        $accessToken = Common::getHugeAmountAccessToken($appId, $secret);

        $appId1 = config('tiktok.huge_amount_yaodao.app_id');
        $secret1 = config('tiktok.huge_amount_yaodao.secret');
        $accessToken1 = Common::getHugeAmountAccessToken($appId1, $secret1);

        $appId24 = config('tiktok.huge_amount_xingcan.app_id');
        $secret24 = config('tiktok.huge_amount_xingcan.secret');
        $accessToken24 = Common::getHugeAmountAccessToken($appId24, $secret24);

        $appId5 = config('tiktok.huge_amount_xingcan.app_id');
        $secret5 = config('tiktok.huge_amount_xingcan.secret');
        $accessToken5 = Common::getHugeAmountAccessToken($appId5, $secret5);

        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');

        $url = 'https://ad.oceanengine.com/open_api/2/report/campaign/get/';
        $url2 = 'https://api.oceanengine.com/open_api/v3.0/report/custom/get/';
        // $hearder['headers'] = ['Access-Token:' . $accessToken];
        if ($params['subject_id'] == 8) {
            $hearder['headers'] = ['Access-Token:' . $accessToken1];
        } elseif ($params['subject_id'] == 24) {
            $hearder['headers'] = ['Access-Token:' . $accessToken24];
        } 
        // elseif (in_array($params['subject_id'], config('tiktok.penshang'))) {
        //     $hearder['headers'] = ['Access-Token:' . $accessToken5];
        // } 
        else {
            $hearder['headers'] = ['Access-Token:' . $accessToken];
        }
        $hearder['json'] = 1;

        $projectId = explode(',', trim($params['project_id']));

        $body = [
            'dimensions'    => ['stat_time_day', 'cdp_project_name'],
            'advertiser_id' => $params['advertiser_id'], // 广告账户id
            'start_time'    => $startDate,
            'end_time'      => $endDate,
            'metrics'       => ['stat_cost'],
            'order_by'      => [
                [
                    'field' => 'stat_time_day',
                    'type'  => 'DESC'
                ]
            ],
            'filters'       => [
                [
                    'field'    => 'cdp_project_id',
                    'type'     => 3,
                    'operator' => 1,
                    'values'   => $projectId // 项目id
                ]
            ]
        ];

        $requestData = [];
        foreach ($body as $k => $val) {
            $requestData[$k] = is_string($val) ? $val : json_encode($val);
        }

        $result = Common::_curl($url2, $requestData, 'GET', $hearder);
        $result = json_decode($result, true);

        if (!$result['code']) {

            if (!empty($result['data']['rows'])) {
                foreach ($result['data']['rows'] as $value) {
                    $realTimeSpend += $value['metrics']['stat_cost'];
                }
            }

        }

        return $realTimeSpend;
    }

    // 获取快手花费
    public function getKwaiCost($params)
    {
        $realTimeSpend = 0;
        $appId = config('kwai.magnetic_force.app_id');
        $secret = config('kwai.magnetic_force.secret');
        $accessToken = Common::getKwaiAccessToken($appId, $secret);

        $hearder['headers'] = ['Access-Token: ' . $accessToken];
        $hearder['json'] = 1;

        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $url = 'https://ad.e.kuaishou.com/rest/openapi/v1/advertiser/fund/daily_flows';

        // 获取花费
        $requestData = [
            'advertiser_id' => intval($params['advertiser_id']),
            'start_date' => $startDate,
            'end_date' => $endDate,
        ];

        $result = Common::_curl($url, $requestData, 'POST', $hearder);
        $result = json_decode($result, true);

        if (!$result['code']) {
            $realTimeSpend = empty($result['data']['details'][0]['daily_charge']) ? 0 : $result['data']['details'][0]['daily_charge']; // 今日花费
        }
        return $realTimeSpend;
    }

    // 获取百度花费
    public function getBaiduCost($params)
    {
        $realTimeSpend = 0;
        $accessToken = Common::getBaiduAccessToken();

        $hearder['json'] = 1;

        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d');
        $url = 'https://api.baidu.com/json/feed/v1/ReportFeedService/getRealTimeFeedData';

        $redis = Cache::store('redis')->handler();
        $redis->select(5);
        $subUserListKey = config('baidu.baidu_sub_user_list');
        $subUserList = $redis->hGetAll($subUserListKey);

        if (empty($subUserList[$params['advertiser_id']])) {
            return $realTimeSpend;
        }

        // 获取成本
        $requestData = [
            'header' => [
                'userName' => $subUserList[$params['advertiser_id']],
                'accessToken' => $accessToken
            ],
            'body' => [
                'realTimeRequestType' => [
                    'performanceData' => ['cost'],
                    'startDate' => $startDate,
                    'endDate' => $endDate,
                    'levelOfDetails' => 2,
                    'reportType' => 700,
                    'unitOfTime' => 5
                ]
            ]
        ];

        $result = Common::_curl($url, $requestData, 'POST', $hearder);
        $result = json_decode($result, true);

        if ($result['header']['desc'] == 'success' && $result['header']['status'] == 0) {
            if (!empty($result['body']['data'])) {
                $realTimeSpend = round($result['body']['data'][0]['kpis'][0], 2);
            }

        }

        return $realTimeSpend;
    }

    // 修改总花费
    public function editSpend($params)
    {
        $id = $this->linkModel->edit([
            'id' => $params['id'],
            'spend' => $params['spend'],
            'updated_at' => time()
        ]);

        return $id ? true : false;
    }

    // 公众号(推广主)列表
    public function getPromotionMainList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [];
        if (!empty($params['id'])) {
            $where = ['id' => $params['id']];
        }
        $data = $this->officialAccountsModel->getPagingDataByWhere($where, $page, $limit, 'id, name, created_at');

        return $data;
    }

    // 查看收入
    public function viewRevenue($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [
            ['official_account_id', '=', $params['id']],
            ['status', '=', 1],
            ['type', 'in', [1, 2]]
        ];

        $data = $this->payRecordModel->getPagingDataByWhere($where, $page, $limit, 'video_id, total_fee, created_at');

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'video_id');

            $videoData = $this->videoModel->getDataByIds($videoIds, 'id, name, cooperation_mode, scale');
            $video = array_column($videoData, NULL, 'id');

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['video_name'] = empty($video[$value['video_id']]) ? '' : $video[$value['video_id']]['name'];
                if (!empty($video[$value['video_id']]) && $video[$value['video_id']]['cooperation_mode'] == 1) {
                    $data['data'][$key]['divide_price'] = $video[$value['video_id']]['scale'] * $value['total_fee'] / 100;
                } else {
                    $data['data'][$key]['divide_price'] = 0;
                }
            }
        }

        return $data;
    }

    // 查看用户
    public function viewUser($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = ['official_account_id' => $params['id']];

        $data = $this->userModel->getPagingDataByWhere($where, $page, $limit, 'id, user_name, money, created_at, last_login_time');

        return $data;
    }
}